import { failData, getUserToken, params, request, response, successData } from '@/utils'
import { ILoginParams } from '@/types/request/user'
import { generateNewUserToken } from '@/utils/jwt'
import UserService from '@/models/mysql/UserService'
import UserTokenService from '@/models/mongo/UserTokenService'

// 用户登录
export const login = async () => {
  const username = params<ILoginParams>('username')
  const user = await UserService.getUserInfoByUsername(username)
  if (!user) {
    return failData({ message: '用户不存在' })
  }
  return successData({ message: '登录成功', data: await generateNewUserToken(user) })
}

// 让token过期
export const expiredToken = async () => {
  const token = getUserToken()
  if (token) {
    await UserTokenService.expiredUserToken(token)
  }
  return successData({ message: '操作成功' })
}

// 用户信息
export const info = () => {
  const user = request().user
  return successData({
    data: {
      user_id: user?.id,
      username: user?.username,
      nickname: user?.nickname,
      avatar: user?.avatar,
      register_at: user?.created_at,
      phone: user?.phone
    }
  })
}

// 用户登出
export const logout = async () => {
  const token = getUserToken()
  if (token) {
    await UserTokenService.blackedUserToken(token)
  }
  return successData({ message: '登出成功' })
}
